<script setup lang="ts">
import { ref, unref } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { useRoute, useRouter } from 'vue-router'
import { saveDataApi } from '@/api/payment'
import { useEventBus } from '@/hooks/event/useEventBus'
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import PaymentWrite from '../Payment/components/PaymentWrite.vue'
import { ElMessage } from 'element-plus'

const { emit } = useEventBus()

const { push, go } = useRouter()

const { t } = useI18n()

const writeRef = ref<ComponentRef<typeof PaymentWrite>>()

const loading = ref(false)

const { query } = useRoute()

const purchaseid = Number(query.id)
const uploadStatus = ref<boolean>(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()

  if (formData) {
    if (!formData.attachment) {
      ElMessage.error('附件为必填')
      return
    }
    loading.value = true
    const res = await saveDataApi(formData)
      .catch(() => {})
      .finally(() => {
        loading.value = false
      })
    if (res) {
      emit('getList', 'add')
      push('/purchase/purchase-order-management')
    }
  }
}
</script>

<template>
  <ContentDetailWrap :title="t('payment.add')" @back="push('/payment-module/payment/page')">
    <PaymentWrite
      ref="writeRef"
      :purchaseid="purchaseid"
      :showUploadProof="false"
      :showChoicePurchase="true"
      @uploading="(status: boolean) => (uploadStatus = status)"
    />

    <template #header>
      <BaseButton @click="go(-1)">
        {{ t('common.back') }}
      </BaseButton>
      <BaseButton type="primary" :disabled="uploadStatus" :loading="loading" @click="save"
        >{{ t('action.save') }}
      </BaseButton>
    </template>
  </ContentDetailWrap>
</template>
@/hooks/event/useEventBus
